package main

import (
	"fmt"
	"os"

	"github.com/sniperHW/kendynet"
	"github.com/tealeg/xlsx"
)

func main() {
	xlFile, err := xlsx.OpenFile("../ErrorCode.xlsx")
	if err != nil {
		panic(err)
	}

	sheet := xlFile.Sheets[0]
	rows := sheet.Rows[3:]

	str :=
		`
package ErrorCode

const(
`

	for _, row := range rows {
		id, _ := row.Cells[0].Int()
		if id >= 0 {
			proto := row.Cells[1].String()
			code := row.Cells[2].String()
			codeName := fmt.Sprintf("%s_%s", proto, code)
			desc := row.Cells[3].String()
			str = str + fmt.Sprintf("	%s = %d //%s\n", codeName, id, desc)
		}
	}
	str = str + ")\n"

	out_path := "../../../../common/ErrorCode/ErrorCode.go"

	f, err := os.OpenFile(out_path, os.O_RDWR, os.ModePerm)
	if err != nil {
		if os.IsNotExist(err) {
			f, err = os.Create(out_path)
			if err != nil {
				kendynet.Errorf("create %s failed:%s", out_path, err.Error())
				return
			}
		} else {
			kendynet.Errorf("open %s failed:%s", out_path, err.Error())
			return
		}
	}

	err = os.Truncate(out_path, 0)

	_, err = f.WriteString(str)

	if nil != err {
		kendynet.Errorf("%s Write error:%s\n", out_path, err.Error())
	} else {
		kendynet.Infof("%s Write ok\n", out_path)
	}

	f.Close()
}
